package com.example.bighomework.fragment;

import android.content.ContentResolver;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import androidx.fragment.app.Fragment;

import com.example.bighomework.R;

import org.checkerframework.checker.nullness.qual.NonNull;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link VideosFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VideosFragment extends Fragment implements SeekBar.OnSeekBarChangeListener, SurfaceHolder.Callback {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private RelativeLayout rl;
    private SurfaceView sv;
    private ImageView play;
    private SeekBar sbar;
    private SurfaceHolder holder;
    private Timer timer;
    private TimerTask timerTask;

    private MediaPlayer mediaPlayer;
    private View view;

    public VideosFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment VideosFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static VideosFragment newInstance(String param1, String param2) {
        VideosFragment fragment = new VideosFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_videos, container, false);
        rl = view.findViewById(R.id.rl);
        sv = view.findViewById(R.id.sv);
        play = view.findViewById(R.id.play);
        sbar = view.findViewById(R.id.sbar);
        sbar.setOnSeekBarChangeListener(this);
        holder = sv.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(this);

        timerTask = new TimerTask() {

            @Override
            public void run() {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    int duration = mediaPlayer.getDuration();
                    sbar.setMax(duration);
                    int current = mediaPlayer.getCurrentPosition();
                    sbar.setProgress(current);
                } else {
                    getActivity().runOnUiThread(()->{
                        play.setImageResource(android.R.drawable.ic_media_play);

                    });
                }
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 500, 500);
        play.setOnClickListener(view1 -> click(view1));
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        if (mediaPlayer != null) {
            mediaPlayer.seekTo(progress);
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        mediaPlayer= new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        Uri parse = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + R.raw.video);
        try {
            mediaPlayer.setDataSource(getContext(),parse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        mediaPlayer.setDisplay(holder);

        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                //mediaPlayer.start();
            }
        });

    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
    }

    public void click(View view){
        if (mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            play.setImageResource(android.R.drawable.ic_media_play);
        }else {
            mediaPlayer.start();
            play.setImageResource(android.R.drawable.ic_media_pause);
        }
    }



    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if (rl.getVisibility()==View.INVISIBLE){
                    rl.setVisibility(View.VISIBLE);
                    CountDownTimer countDownTimer = new CountDownTimer(3000, 1000) {
                        @Override
                        public void onTick(long l) {
                            System.out.println(l);
                        }

                        @Override
                        public void onFinish() {
                            rl.setVisibility(View.INVISIBLE);
                        }
                    };
                    countDownTimer.start();

                }else if (rl.getVisibility()==View.VISIBLE){
                    rl.setVisibility(View.INVISIBLE);
                }
                break;
        }
        return true;
    }


    @Override
    public void onDestroy() {
        if (timer!=null) {
            timer.cancel();
            timerTask.cancel();
            timer = null;
            timerTask = null;
            mediaPlayer.release();
            mediaPlayer = null;
        }
        super.onDestroy();
    }
}